const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const router = express.Router();
const User = require('../models/user'); // 引入Sequelize模型
const { jwtSecret } = require('../config');
const {Op} = require('sequelize');

const saltRounds = 10;

// 用户注册
router.post('/register', async (req, res) => {
    try {
        const { username, password } = req.body;

        // 检查用户名是否已存在
        const existingUser = await User.findOne({
            where: {
                username
            },
        });
        if (existingUser) {
            return res.status(400).json({ message: '用户名已存在' });
        }

        // 密码加密并创建用户
        const hashedPassword = await bcrypt.hash(password, saltRounds);
        const newUser = await User.create({
            username,
            password: hashedPassword,
            is_admin: false
        });

        res.send({
            code: 200,
            message: '注册成功',
            userId: newUser.id
        });
    } catch (error) {
        console.error('注册错误:', error);
        res.send({ message: '服务器错误', code: 500 });
    }
});

// 用户登录
router.post('/login', async (req, res) => {
    try {
        const { username, password } = req.body;

        // 查找用户
        const user = await User.findOne({ where: { username } });
        if (!user) {
            return res.send({ message: '用户名或密码错误' });
        }

        // 验证密码
        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) {
            return res.send({ message: '用户名或密码错误' });
        }

        // 生成JWT
        const token = jwt.sign(
            { userId: user.id, isAdmin: user.is_admin },
            jwtSecret,
            { expiresIn: '24h' }
        );

        res.send({
            code: 200,
            message: '登录成功',
            token,
            user: {
                id: user.id,
                username: user.username,
                isAdmin: user.is_admin
            }
        });
    } catch (error) {
        console.error('登录错误:', error);
        res.send({ message: '服务器错误！！！' });
    }
});

// 获取用户信息
router.get('/info', async (req, res) => {
    try {
        const token = req.headers.authorization?.split(' ')[1];
        if (!token) {
            return res.send({ message: '未提供认证令牌' });
        }

        const decoded = jwt.verify(token, jwtSecret);

        // 查找用户
        const user = await User.findByPk(decoded.userId, {
            attributes: ['id', 'username', 'is_admin']
        });

        if (!user) {
            return res.send({ message: '用户不存在', code: 500 });
        }

        res.send({
            code: 200,
            user
        });
    } catch (error) {
        console.error('获取用户信息错误:', error);
        if (error.name === 'JsonWebTokenError') {
            return res.send({ message: '无效的令牌' });
        }
        res.send({ message: '服务器错误' });
    }
});

// 查询所有用户
router.get('/list', async (req, res) => {
    try {
        const {username} = req.query

        const where = {}
        if(username){
            where.username = {
                [Op.like]: `%${username}%`
            }
        }

        const users = await User.findAll({
            where,
            attributes: ['id', 'username', 'is_admin']
        });
        res.send({
            code: 200,
            data: users
        });
    } catch (error) {
        console.error('获取用户列表失败:', error);
        res.send({code:500, message: error.message });
    }
})

//修改某个用户
router.post('/update', async (req, res) => {
    try {
        const {id, username, is_admin } = req.body;
        // 检查用户是否存在
        const user = await User.findByPk(id);
        if (!user) {
            return res.send({code: 500, message: '用户不存在' });
        }
        // 更新用户信息
        await user.update({
            username,
            is_admin
        });
        res.send({code: 200, message: '修改成功'})
    }catch (e){
        res.send({code: 500, message: e.message})
    }
})


//删除
router.delete('/delete', async (req, res)=> {
    try {
        const {id} = req.body;
        const user = await User.findByPk(id);
        if (!user) {
            return res.send({code: 500, message: '用户不存在' });
        }
        await user.destroy()
        res.send({code: 200, message: '删除成功'})
    }catch (e){
        res.send({code: 500, message: e.message})
    }
})
module.exports = router;
